package com.wen.wenda.service.scoring.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wen.wenda.annotation.ScoringStrategyConfig;
import com.wen.wenda.constant.AppConstant;
import com.wen.wenda.model.domain.App;
import com.wen.wenda.model.domain.Question;
import com.wen.wenda.model.domain.ScoringResult;
import com.wen.wenda.model.domain.UserAnswer;
import com.wen.wenda.model.request.question.QuestionContentDTO;
import com.wen.wenda.service.QuestionService;
import com.wen.wenda.service.ScoringResultService;
import com.wen.wenda.service.scoring.ScoringStrategy;
import jakarta.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义测评类
 *
 * @author wen
 */
@ScoringStrategyConfig(appType = AppConstant.EVALUATION_VALUE, scoringStrategy = AppConstant.CUSTOM_SCORING_STRATEGY_VALUE)
public class CustomTestScoringStrategy implements ScoringStrategy {

    @Resource
    private QuestionService questionService;

    @Resource
    private ScoringResultService scoringResultService;

    @Override
    public UserAnswer executeScoring(List<String> choices, App app) {
        // 1. 得到题目和题目结果信息
        Long appId = app.getId();
        Question question = questionService.getOne(
                Wrappers.lambdaQuery(Question.class).eq(Question::getAppId, appId)
        );
        List<ScoringResult> scoringResultList = scoringResultService.list(
                Wrappers.lambdaQuery(ScoringResult.class)
                        .eq(ScoringResult::getAppId, appId)
        );
        // 2. 统计用户每个选择相对应的属性个数
        // 初始化一个 Map 记录每个选项的选择次数
        Map<String, Integer> optionCount = new HashMap<>();

        String questionContent = question.getQuestionContent();
        List<QuestionContentDTO> questionContentDTOList = JSONUtil.toList(questionContent, QuestionContentDTO.class);
        // 遍历题目列表
        for (QuestionContentDTO questionContentDTO : questionContentDTOList) {
            // 遍历用户答案列表
            choices.forEach(answer ->
                    // 遍历题目中的选项
                    questionContentDTO.getOptions().stream()
                            .filter(option -> option.getKey().equals(answer))
                            .forEach(option -> {
                                String result = option.getResult();
                                optionCount.putIfAbsent(result, 0);
                                optionCount.put(result, optionCount.get(result) + 1);
                            })
            );
        }
        // 3. 遍历每种评分结果，计算哪个结果的得分更高
        ScoringResult maxScoringResult = scoringResultList.get(0);
        int maxScore = 0;

        for (ScoringResult scoringResult : scoringResultList) {
            List<String> resultProp = JSONUtil.toList(scoringResult.getResultProp(), String.class);
            int score = resultProp.stream()
                    .mapToInt(prop -> optionCount.getOrDefault(prop, 0))
                    .sum();

            if (score > maxScore) {
                maxScore = score;
                maxScoringResult = scoringResult;
            }
        }
        // 4. 构造返回值，填充答案的属性
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        userAnswer.setResultId(maxScoringResult.getId());
        userAnswer.setResultName(maxScoringResult.getResultName());
        userAnswer.setResultDesc(maxScoringResult.getResultDesc());
        userAnswer.setResultPicture(maxScoringResult.getResultPicture());
        return userAnswer;
    }
}
